#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging

from aiohttp import web

from com.chenxiaojie.mvc.user_controller import cookies2user


async def user_auth_factory(app, handler):
    async def auth(request):
        if not request.path.startswith("/static"):
            request.__user__ = None
            user = await cookies2user(request.cookies)
            if user:
                logging.info('set current user: %s' % user.email)
                request.__user__ = user
            if request.path.startswith('/manage/') and (request.__user__ is None or not request.__user__.admin):
                return web.HTTPFound('/user/login.html')
        return (await handler(request))

    return auth